package main

import (
	"fmt"
	"runtime"
)

// output:
// 228 KB
// 472384 KB
// 300562 KB
func main() {
	printAlloc()

	n := 1_000_000
	m := make(map[int][128]byte) // 初始化2-3kb？..
	//m := make(map[int]int) // 初始化2-3kb？..
	printAlloc()
	fmt.Printf("%+v\n", m)

	empty := [128]byte{}
	for i := 0; i < n; i++ { // Adds 1 million elements
		m[i] = empty
	}
	fmt.Printf("%+v\n", m)
	printAlloc()

	for i := 0; i < n; i++ { // Deletes 1 million elements
		delete(m, i)
	}

	// fmt.Printf("%+v\n", m)
	runtime.GC() // Triggers a manual GC
	fmt.Printf("%+v\n", m)
	printAlloc()

	// map 会预留部分内存.
	// runtime.KeepAlive(m) // Keeps a reference to m so that the map isn’t collected
	// println(len(m))
	runtime.KeepAlive(m) // 增加一次引用

}

func printAlloc() {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	fmt.Printf("%d KB\n", m.HeapAlloc/1024)
}
